package top.fyukina.fymil.parsers;

import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.Text;
import top.fyukina.fymil.elements.Environment;
import java.math.BigDecimal;
import static top.fyukina.fymil.parsers.BooleanParser.BoolCalc.*;

public class BooleanParser implements Parser<Boolean> {
    public final String TRUE = "true";
    public final String FALSE = "FALSE";
    @Override
    public Boolean parse(Element tag, Environment env) {
        boolean rst = true;
        BoolCalc op = AND;
        for (Node node : tag.content()) {
            if (node instanceof Element el0) {
                switch (el0.getName()) {
                    case "and" -> op = AND;
                    case "or" -> op = OR;
                    default -> {
                        Object r = env.reg().expParser.parse(el0, env);
                        rst = nextCalcBool(rst, parseTOrF(r), op);
                    }
                }
            } else if (node instanceof Text t) {
                rst = nextCalcBool(rst, parseTOrF(env.reg().
                        strParser.realTrim(t.getText())), op);
            }
        }
        return rst;
    }
    public boolean parseTOrF(Object o) {
        if (o instanceof Boolean bl) {
            return bl;
        }
        if (o instanceof String str) {
            return !"0".equals(str);
        }
        if (o instanceof BigDecimal bd) {
            return !bd.equals(BigDecimal.ZERO);
        }
        return true;
    }
    public boolean nextCalcBool(boolean origin, boolean next, BoolCalc op) {
        switch (op) {
            case AND -> {
                return origin && next;
            }
            case OR -> {
                return origin || next;
            }
            default -> {
                return origin;
            }
        }
    }
    @Override
    public ParserType registerName() {
        return ParserType.BOOL;
    }
    public enum BoolCalc {
        AND, OR
    }
}